package com.guyaogg.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.guyaogg.common.constant.AuthServerConstant;
import com.guyaogg.common.utils.R;
import com.guyaogg.common.vo.MemberRespVO;
import com.guyaogg.gulimall.auth.feign.MemberFeignService;
import com.guyaogg.gulimall.auth.vo.UserLoginVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
 * @author 顾遥
 */
@Slf4j
@Controller
public class LoginController {

    private final MemberFeignService memberFeignService;

    public LoginController(MemberFeignService memberFeignService) {
        this.memberFeignService = memberFeignService;
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if(attribute == null){
            return "login";
        }else {
            return "redirect:http://gulimall.com";
        }
    }

    @PostMapping("/login")
    public String login(UserLoginVO vo, RedirectAttributes redirectAttributes, HttpSession session) {
        log.debug("登录接收消息：{}", vo);

        // 远程登录
        R r = memberFeignService.login(vo);
        if (r.getCode() == 0) {
            // 成功
            MemberRespVO resp = r.getData(new TypeReference<MemberRespVO>() {
            });
            session.setAttribute(AuthServerConstant.LOGIN_USER, resp);
            return "redirect:http://gulimall.com";
        } else {
            HashMap<String, String> errors = new HashMap<>(1);
            String msg = r.getData("msg", new TypeReference<String>() {
            });
            errors.put("msg", msg);
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }

    }



}
